package client.comm.commlib.widget

import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.ViewGroup
import androidx.core.view.*
import client.comm.commlib.dipToPx


class SearchHisWrap @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : ViewGroup(context, attrs, defStyleAttr) {

    val spaceAround = dipToPx(resources, 10f).toInt()
    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {

        Log.d("SearchWrapWidth", "oo$t")
        Log.d("SearchWrapWidth", "oo$b")

        var tmpT: Int = 0
        var tmpL: Int = l
        for ((i, v) in children.withIndex()) {
            if ((tmpL + v.measuredWidth + spaceAround * 2) > r) {
                tmpT = spaceAround + v.measuredHeight + tmpT
                tmpL = l
            }
            v.layout(
                tmpL + spaceAround,
                tmpT + spaceAround,
                (tmpL + v.measuredWidth + spaceAround),
                (tmpT + v.measuredHeight + spaceAround)
            )
            tmpL = tmpL + v.measuredWidth + spaceAround
        }
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val width = MeasureSpec.getSize(widthMeasureSpec)
        var height = 0
        var tmpWidth = 0
        for ((i, v) in children.withIndex()) {
            measureChild(v, widthMeasureSpec, heightMeasureSpec)
            tmpWidth += v.measuredWidth + spaceAround
            if (tmpWidth > width - spaceAround || i == 0) {
                height += v.measuredHeight + spaceAround
                tmpWidth = 0
            }
        }
        setMeasuredDimension(
            widthMeasureSpec,
            MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)
        )
    }
}